﻿/*********************************************************
 * 开发人员：Tony
 * 创建时间：2013-9-29 16:36:46
 * 描述说明：
 * 
 * 更改历史：
 * 
 * *******************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Web;
using System.Security.Authentication;

namespace Beway.ValueAdded.Util
{
    public static class HttpHelper
    {
        /// <summary>
        /// 发送get请求
        /// </summary>
        /// <param name="Url">请求地址</param>
        /// <param name="PostDataStr">请求参数</param>
        /// <returns>请求地址响应内容</returns>
        public static string HttpGet(string Url, string PostDataStr)
        {
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Url + (PostDataStr == "" ? "" : "?") + PostDataStr);
            Request.Method = "GET";
            Request.ContentType = "text/html;charset=utf-8";

            HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
            Stream Stream = Response.GetResponseStream();
            StreamReader StreamReader = new StreamReader(Stream, Encoding.GetEncoding("utf-8"));
            string Result = StreamReader.ReadToEnd();
            StreamReader.Close();
            Stream.Close();

            return Result;
        }

       
		private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
 


        /// <summary>
        /// Http请求动作
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="method">可以是POST,GET,PUT,DELETE</param>
        /// <param name="whc">HTTP请求协议标头</param>
        /// <returns></returns>
         public static string HttpAction(HttpWebRequest webReq,string content="")
         {
            //HttpWebRequest.Timeout = 1000 * 60;
            //HttpWebRequest.KeepAlive = false;
            //HttpWebRequest.ProtocolVersion = HttpVersion.Version11;  
                      
            webReq.ContentType = "application/xml";
            if (webReq.RequestUri.ToString().StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //服务器端采用tls1.2协议，目前.net4.0&4.5均没有实现(4.6中已实现)，所以使用此方法解决----生产环境不支持此方式。。。。。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                 
                //解决https请求证书无效时请求失败的问题 by lmh 20160428
                ServicePointManager.ServerCertificateValidationCallback = new
                 RemoteCertificateValidationCallback
                 (
                    delegate { return true; }
                 );
            }      

            if (!string.IsNullOrWhiteSpace(content))
            {
                byte[] ByteContent = Encoding.UTF8.GetBytes(content);
                webReq.ContentLength = ByteContent.Length;
                Stream OutputStream = webReq.GetRequestStream();
                OutputStream.Write(ByteContent, 0, ByteContent.Length);
                OutputStream.Close();
            }

            string ret = string.Empty;
             try
             {
                 using (HttpWebResponse Response = webReq.GetResponse() as HttpWebResponse)
                 {
                     Stream Stream = Response.GetResponseStream();

                     StreamReader reader = new StreamReader(Stream);
                     ret = reader.ReadToEnd();
                 }
             }
             catch (Exception Ex)
             {
                 //return "fuck------------"+Ex.Message;
             }

             return ret;

         }

		/// <summary>
		/// 发送Post数据流
		/// </summary>
		/// <param name="RequestUrl">请求Url</param>
		/// <param name="Content">数据内容能数，如为键/值对，则需要拼接为字符串,如p1=aaa&p2=bbb&p3=ccc</param>
		/// <param name="RequestEncoding">字符编码</param>
		/// <param name="Cookies">Cookie集合</param>
		/// <returns></returns>
		public static string HttpPost(string RequestUrl, string Content, Encoding RequestEncoding = null, CookieCollection Cookies = null) {
			if (RequestEncoding == null)
				RequestEncoding = Encoding.UTF8;
			byte[] ByteContent = RequestEncoding.GetBytes(Content);

			HttpWebRequest HttpWebRequest = WebRequest.Create(RequestUrl) as HttpWebRequest;
			HttpWebRequest.UserAgent = DefaultUserAgent;
			HttpWebRequest.Method = "POST";
			HttpWebRequest.ContentType = "application/x-www-form-urlencoded";
			HttpWebRequest.ContentLength = ByteContent.Length;

			//解决https请求证书无效时请求失败的问题 by lmh 20160428
			ServicePointManager.ServerCertificateValidationCallback = new
			RemoteCertificateValidationCallback
			(
			   delegate { return true; }
			);

			if (Cookies != null) {
				HttpWebRequest.CookieContainer = new CookieContainer();
				HttpWebRequest.CookieContainer.Add(Cookies);
			}

			try {
				using (Stream OutputStream = HttpWebRequest.GetRequestStream()) {
					OutputStream.Write(ByteContent, 0, ByteContent.Length);
					OutputStream.Close();
				}
			}
			catch (Exception Ex) {
				//return Ex.Message;
			}

			string ret = string.Empty;

			try {
				using (HttpWebResponse Response = HttpWebRequest.GetResponse() as HttpWebResponse) {
					Stream Stream = Response.GetResponseStream();
					//XDocument XDoc = XDocument.Load(Stream);

					StreamReader reader = new StreamReader(Stream);
					ret = reader.ReadToEnd();
				}
			}
			catch (Exception Ex) {
				//return "fuck------------"+Ex.Message;
			}

			return ret;
		}

        /// <summary>
        /// 根据request对象，获取完整的Url，结尾没有"/"
        /// </summary>
        /// <param name="request">HttpRequestBase对象</param>
        /// <returns></returns>
        public static string GetHttpUrl(HttpRequestBase request)
        {
            string siteUrl = "http://" + request.Url.Host;
            if (request.IsSecureConnection)
            {
                siteUrl = "https://" + request.Url.Host;
            }
            int port = request.Url.Port;
            if (port != 80 && port != 443)
            {
                siteUrl = siteUrl + ":" + port;
            }
            return siteUrl;
        }
    }
}
